package cn.life.common.support.check;

import cn.life.business.user.dao.UserDao;
import cn.life.common.entity.model.CMessage;
import cn.life.common.entity.model.MyCommon;
import cn.life.common.test.Test;
import cn.life.common.utils.BodyReaderHttpServletRequestWrapper;
import cn.life.common.utils.EncryptPwdUtil;
import cn.life.common.utils.JwtUtil;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * @Description:    用户信息拦截器
 *
 * @Author 李佳明
 * @Date 2018/7/17 0017 下午 1:45
 */
public class UserInterceptorHandler implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(UserInterceptorHandler.class);

    /** 登录用户信息session中的key */
    private String sessionKey = MyCommon.MY_SESSION_KEY;

    public static void main(String[] args){
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Param Start<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        logger.debug("context");
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Param End<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        ServletRequest requestWrapper = null;
        if(request instanceof HttpServletRequest) {
            requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
        }
        String param= null;
        BufferedReader streamReader = new BufferedReader( new InputStreamReader(requestWrapper.getInputStream(), "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);

        /*if(responseStrBuilder != null && !responseStrBuilder.toString().equals("") && responseStrBuilder.length() > 0){
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            param= jsonObject.toJSONString();
            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Param Start<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
            logger.debug("URL : " + request.getRequestURI());
            logger.debug("Param : " + param);
            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Param End<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        }*/

        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("factoryCookie")){
                    sessionKey = cookie.getValue();
                }
            }
        }

        // 获取session中存放的用户信息
        if(sessionKey != null && !sessionKey.equals("")){
            sessionKey = EncryptPwdUtil.decryptPwd(sessionKey);
        }
        Object sessionMember = WebUtils.getSessionAttribute(request, sessionKey);
        if(sessionMember != null){
            return true;
        }

        String token = request.getHeader("token");
        if(request.getServletPath().contains("go_to_") || request.getServletPath().contains("web/")|| request.getServletPath().contains("login")){
            return true;
        }
        if(null == token){
            writeJson(response,CMessage.fail("1001","当前用户信息已失效，请重新登录"));
            return false;
        }else{
            Claims claims = JwtUtil.verifyToken(token);
            if(claims == null){
                writeJson(response,CMessage.fail("1001","当前用户信息已失效，请重新登录"));
                return false;
            }
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    /**
     * 输出Json
     *
     * @param response
     * @param obj
     */
    public void writeJson(HttpServletResponse response, Object obj) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(JSONObject.toJSONString(obj));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
